package handler

import (
	"cartApi/proto/cartApi"
	"context"
	"encoding/json"
	"errors"
	"gitee.com/wendyRose/cart/proto/cart"
	log "github.com/micro/go-micro/v2/logger"
	"strconv"
)

type CartApi struct{
	CartService cart.CartService
}

// CartApi.Call is called by the API as /cartApi/call with post body {"name": "foo"}
func (e *CartApi) FindAll(ctx context.Context, req *cartApi.Request, rsp *cartApi.Response) error {
	log.Info("接收到/cartApi/findAll访问请求")
	if _,ok := req.Get ["user_id"]; !ok {
		rsp.StatusCode = 500
		return errors.New("参数异常")
	}
	userIdString := req.Get["user_id"].Values[0]
	userId, err := strconv.ParseInt(userIdString, 10, 64)
	if err != nil {
		return err
	}
	cartAll, err := e.CartService.GetAll(context.TODO(), &cart.CartFindAll{UserId: userId})
	b, err := json.Marshal(cartAll)
	if err != nil {
		return err
	}
	rsp.StatusCode = 200
	rsp.Body = string(b)
	return nil
}
